/*
 *
 *   ReBayCT: a tool for classification on a Thesaurus
 *
 *	For details see:
 *	 L. M. de Campos, A. E. Romero, Bayesian Network Models for Hierarchical Text 
 *	Classification from a Thesaurus, Int. J. Approx. Reasoning 50(7): 932-944 (2009).
 *
 *
 *   Copyright (C) 2006-2008 Alfonso E. Romero <alfonsoeromero (AT) gmail (DOT) com>
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

/*
 * Rebayct.java
 *
 * Created on 14/05/2011, 04:15
 */
package programs;

import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import supervisedClassifier.SupervisedBN;
import thesaurus.ThesaurusStringIndexer;
import unsupervisedClassifier.*;

/**
 *
 * @author  aeromero
 */
public class Rebayct extends javax.swing.JFrame {

    ClassifierModel cm;
    boolean isStopwordsListLoaded;
    boolean isThesaurusIndexLoaded;
    boolean isTextIndexLoaded;
    String stopwords;
    String thesaurusIndex;
    String textIndex;
    double w_hier, w_equiv;

    /** Creates new form Parlamento */
    public Rebayct() {

        initComponents();
        this.setLocationRelativeTo(null);
        this.setExtendedState(this.getExtendedState() | javax.swing.JFrame.MAXIMIZED_BOTH);
        this.isThesaurusIndexLoaded = false;
        this.isStopwordsListLoaded = false;
        this.isTextIndexLoaded = false;
        ThesaurusStringIndexer.setStemLanguage("es");
        /*
        // replace this with your favorite "thesaurus thesaurusIndex" and "stopwords list"
        cm = new BNClassifier("congreso1", "otra.txt", true, true, true);*/
    }

    private boolean parseWeights() {
        boolean result = true;
        try {
            this.w_hier = Double.parseDouble(this.hierarchy.getText());

            if (w_hier < 0.0 || w_hier > 1.0) {
                result = false;
                JOptionPane.showMessageDialog(this, "El peso de la jerarquía debe estar entre 0 y 1", "¡Error!", JOptionPane.ERROR_MESSAGE);
            }

        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, "El valor seleccionado para el peso de la jerarquía no es un flotante válido", "¡Error!", JOptionPane.ERROR_MESSAGE);
            result = false;
        }

        if (result) {
            try {
                this.w_equiv = Double.parseDouble(this.eqivalence.getText());

                if (w_equiv < 0.0 || w_equiv > 1.0) {
                    result = false;
                    JOptionPane.showMessageDialog(this, "El peso de las relaciones de equivalencia debe estar entre 0 y 1", "¡Error!", JOptionPane.ERROR_MESSAGE);
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "El valor seleccionado para el peso de las relaciones de equivalencia no es un flotante válido", "¡Error!", JOptionPane.ERROR_MESSAGE);
                result = false;
            }
        }
        return result;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel2 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jPanel3 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        eqivalence = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        hierarchy = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArea2 = new javax.swing.JTextArea();
        jPanel5 = new javax.swing.JPanel();
        jPanel6 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jButton3 = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        jTextField3 = new javax.swing.JTextField();
        jButton4 = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JSeparator();
        jSeparator1 = new javax.swing.JSeparator();

        jLabel2.setText("jLabel2");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle(":: Clasificación automática de iniciativas ::");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setLocationByPlatform(true);
        setMaximizedBounds(new java.awt.Rectangle(0, 0, 800, 600));

        jPanel1.setMaximumSize(new java.awt.Dimension(2000, 2000));
        jPanel1.setMinimumSize(new java.awt.Dimension(100, 100));
        jPanel1.setPreferredSize(new java.awt.Dimension(100, 100));
        jPanel1.setLayout(new java.awt.BorderLayout(2, 2));

        jPanel2.setLayout(new java.awt.GridLayout(1, 0, 5, 5));

        jLabel1.setText("Texto para clasificar:");
        jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
        jPanel2.add(jLabel1);

        jPanel1.add(jPanel2, java.awt.BorderLayout.NORTH);

        jTextArea1.setColumns(20);
        jTextArea1.setRows(2);
        jTextArea1.setMaximumSize(new java.awt.Dimension(10, 10));
        jTextArea1.setPreferredSize(new java.awt.Dimension(100, 30));
        jScrollPane1.setViewportView(jTextArea1);

        jPanel1.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jPanel3.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 10, 5));

        jLabel5.setText("Peso de las relaciones de equivalencia");
        jPanel3.add(jLabel5);

        eqivalence.setText("0.9");
        eqivalence.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                eqivalenceActionPerformed(evt);
            }
        });
        jPanel3.add(eqivalence);

        jLabel6.setText("Peso de la jerarquía");
        jPanel3.add(jLabel6);

        hierarchy.setText("0.9");
        jPanel3.add(hierarchy);

        jButton1.setText("Clasificar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel3.add(jButton1);

        jPanel1.add(jPanel3, java.awt.BorderLayout.PAGE_END);

        getContentPane().add(jPanel1, java.awt.BorderLayout.NORTH);

        jPanel4.setLayout(new java.awt.BorderLayout());

        jTextArea2.setColumns(20);
        jTextArea2.setEditable(false);
        jTextArea2.setRows(5);
        jScrollPane2.setViewportView(jTextArea2);

        jPanel4.add(jScrollPane2, java.awt.BorderLayout.CENTER);

        jPanel5.setLayout(new java.awt.BorderLayout(3, 3));

        jPanel6.setLayout(new java.awt.GridLayout(3, 3, 5, 5));

        jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel3.setText("Lista de stopwords:");
        jPanel6.add(jLabel3);

        jTextField1.setEditable(false);
        jPanel6.add(jTextField1);

        jButton2.setText("Cargar...");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel6.add(jButton2);

        jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel4.setText("Índice del tesauro:");
        jPanel6.add(jLabel4);

        jTextField2.setEditable(false);
        jPanel6.add(jTextField2);

        jButton3.setText("Cargar...");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        jPanel6.add(jButton3);

        jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel7.setText("Índice textual");
        jPanel6.add(jLabel7);

        jTextField3.setEditable(false);
        jPanel6.add(jTextField3);

        jButton4.setText("Cargar...");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        jPanel6.add(jButton4);

        jPanel5.add(jPanel6, java.awt.BorderLayout.CENTER);
        jPanel5.add(jSeparator2, java.awt.BorderLayout.PAGE_START);

        jPanel4.add(jPanel5, java.awt.BorderLayout.PAGE_END);
        jPanel4.add(jSeparator1, java.awt.BorderLayout.PAGE_START);

        getContentPane().add(jPanel4, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
        if (this.jTextArea1.getText().length() > 0) {
            String s = this.jTextArea1.getText();

            if (!this.isThesaurusIndexLoaded) {
                JOptionPane.showMessageDialog(this, "Debes cargar un índice del tesauro", "Aviso", JOptionPane.WARNING_MESSAGE);

            } else if (!this.isStopwordsListLoaded) {
                JOptionPane.showMessageDialog(this, "Debes cargar una lista de stopwords", "Aviso", JOptionPane.WARNING_MESSAGE);

            } else if (!this.isTextIndexLoaded) {
                JOptionPane.showMessageDialog(this, "Debes cargar un índice textual", "Aviso", JOptionPane.WARNING_MESSAGE);
            } else if (this.parseWeights()) {

                //List<Result> lr = this.cm.classifyString(s);
                SupervisedBN bn = new SupervisedBN(this.textIndex, this.thesaurusIndex, this.stopwords,
                        true, false, false, this.w_equiv, this.w_hier);

                this.jTextArea2.setText("");
                this.jTextArea2.repaint();

                List<Result> lr = bn.classifyString(s);

                StringBuilder sb = new StringBuilder("");
                for (Result r : lr) {
                    sb.append(r.getProb()).append("\t").append(r.getDescriptor().getDescription()).append("\n");
                }

                this.jTextArea2.setText(sb.toString());
                this.jTextArea2.repaint();
            }

        } else {
            JOptionPane.showMessageDialog(this, "No has introducido texto", "Aviso", JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void eqivalenceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_eqivalenceActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_eqivalenceActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        JFileChooser fileChooser = new JFileChooser();
        int seleccion = fileChooser.showOpenDialog(this);

        if (seleccion == JFileChooser.APPROVE_OPTION) {
            this.stopwords = fileChooser.getSelectedFile().getAbsolutePath();
            this.isStopwordsListLoaded = true;
        } else {
            this.stopwords = "";
            this.isStopwordsListLoaded = false;
        }
        this.jTextField1.setText(this.stopwords);
        this.repaint();

    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        JFileChooser fileChooser = new JFileChooser();
        int seleccion = fileChooser.showOpenDialog(this);

        if (seleccion == JFileChooser.APPROVE_OPTION) {
            this.thesaurusIndex = fileChooser.getSelectedFile().getAbsolutePath();
            this.isThesaurusIndexLoaded = true;
        } else {
            this.thesaurusIndex = "";
            this.isThesaurusIndexLoaded = false;
        }
        this.jTextField2.setText(this.thesaurusIndex);
        this.repaint();
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        // TODO add your handling code here:
        // TODO add your handling code here:
        JFileChooser fileChooser = new JFileChooser();
        int seleccion = fileChooser.showOpenDialog(this);

        if (seleccion == JFileChooser.APPROVE_OPTION) {
            this.textIndex = fileChooser.getSelectedFile().getAbsolutePath();
            this.isTextIndexLoaded = true;
        } else {
            this.textIndex = "";
            this.isTextIndexLoaded = false;
        }
        this.jTextField3.setText(this.textIndex);
        this.repaint();
    }//GEN-LAST:event_jButton4ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Rebayct().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField eqivalence;
    private javax.swing.JTextField hierarchy;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextArea jTextArea2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    // End of variables declaration//GEN-END:variables
}
